<template>
  <el-card>
    <template #header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>发布文章</el-breadcrumb-item>
      </el-breadcrumb>
    </template>
    <el-form label-width="100px" :model="form" :rules="rules" ref="form">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入文章标题"> </el-input>
      </el-form-item>
      <el-form-item label="频道" prop="channel_id">
        <HmSelect :form="form"></HmSelect>
      </el-form-item>
      <!-- el-form
    1:el-form
          model
          rules
          ref
    2:el-form-item
          prop
    3:表单元素  v-model绑定
    4:rules:{
      prop的值:[
      {required:true,message:错误信息,trigger:'change/blur'},
      {min:最小长度,max:最大长度,message:错误信息,trigger:'change/blur'},
      {validator:(rule,value,callback)=>{
        rule:规则
        value:当前项的值
        callback:如果验证通过 callback()  验证不通过  callback(new Error(错误信息))
      },trigger:'change/blur'}
      ]
    }
    this.$refs.ref的值.validate((result)=>{
      result:true验证通过false验证失败
    })
    this.$refs.ref值.validateField(["prop的值"],(errorMessage)=>{
      errorMessage:如果为空，验证通过,如果不为空，验证失败
    })
     -->
      <el-form-item label="封面" prop="cover">
        <el-radio-group v-model="form.cover.type" @change="radioChange">
          <el-radio :label="1">单图</el-radio>
          <el-radio :label="3">三图</el-radio>
          <el-radio :label="0">无图</el-radio>
          <el-radio :label="-1">自动</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <div v-if="bol">
          <el-upload
            accept="#"
            list-type="picture-card"
            :file-list="fileList"
            :action="baseUrl + '/v1_0/upload'"
            name="image"
            :on-success="onSuccess"
            :limit="form.cover.type"
            :before-upload="beforeUpload"
            :on-remove="onRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <quillEditor
          v-model="form.content"
          @change="editorChange"
        ></quillEditor>
      </el-form-item>
      <el-form-item>
        <div v-if="!$route.query.id">
          <!-- 如果没有 id 则是发布文章 -->
          <el-button type="primary" @click="submit(false)">发布文章</el-button>
          <el-button @click="submit(true)">存入草稿</el-button>
        </div>
        <div v-else>
          <!-- 如果有，就是修改文章 -->
          <el-button type="primary" @click="edit(false)">修改文章</el-button>
          <el-button @click="edit(true)">存入草稿</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";
import { createArticles, mpArticlesGet, apArticlesPut } from "@/api/index.js";

export default {
  components: {
    quillEditor
  },
  computed: {
    fileList() {
      return this.form.cover.images.map(item => {
        return { url: item };
      });
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_URL,
      // 后端要的数据都存在form这个对象中
      form: {
        title: "",
        content: "",
        cover: {
          type: 1,
          images: []
        },
        channel_id: ""
      },
      bol: true,
      rules: {
        title: [{ required: true, message: "必填", trigger: "change" }],
        content: [{ required: true, message: "必填", trigger: "change" }],
        cover: [
          { required: true, message: "必填", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              console.log(value);
              if (value.type > 0) {
                value.images.length === value.type
                  ? callback()
                  : callback(new Error(`请上传${value.type}张图片`));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ],
        channel_id: [{ required: true, message: "必填", trigger: "change" }]
      }
    };
  },
  methods: {
    // 上传成功回调函数
    onSuccess(res) {
      this.form.cover.images.push(res.data.url);
      this.$refs.form.validateField(["cover"]);
    },

    radioChange() {
      this.form.cover.images = [];
      this.bol = false;
      this.$nextTick(() => {
        this.bol = true;
      });
    },
    // 文件传给后端前的回调函数
    beforeUpload(file) {
      const isImage = file.type === "image/png" || file.type === "image/jpg";
      const isLimit2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error("请上传png或者ing格式图片");
      }
      if (!isLimit2M) {
        this.$message.error("请上传少于2m的图片");
      }
      return isImage && isLimit2M;
    },

    onRemove(file) {
      const _index = this.form.cover.images.findIndex(
        item => item === file.url
      );
      this.form.cover.images.splice(_index, 1);
    },
    // 发布文章
    submit(draft) {
      this.$refs.form.validate(async result => {
        if (result) {
          const res = await createArticles(this.form, draft);
          this.$message.success(draft ? "存储草稿成功" : "发表文章成功");
          this.$router.push("/article");
        }
      });
    },
    // 编辑
    edit(bol) {
      this.$refs.form.validate(async result => {
        if (result) {
          const res = await apArticlesPut(this.form, bol);
          this.$message.success(bol ? "修改草稿成功" : "修改文章成功");
          this.$router.push("/article");
        }
      });
    },
    editorChange() {
      this.$refs.form.validateField(["content"]);
    },
    // 通过查询参数，id 获取文章详情页
    async getInfo() {
      const res = await mpArticlesGet(this.$route.query.id);
      this.form = res.data;
    }
  },
  created() {
    // $router   $route
    if (this.$route.query.id) {
      // 获取文章详情
      this.getInfo();
    }
  }
};
</script>
<style lang="less" scoped>
// 这里要加 v-deep 是因为要修改 quillEditor 这个组件里的样式。
// scoped 模式，修改不到，所以要加
::v-deep .ql-editor {
  min-height: 150px;
}
</style>
